<template>
  <div>
    <el-row class="nav">
      <span class="font-weight">自定义字段</span>
    </el-row>
    <el-divider></el-divider>
    <el-form :inline="true"
             class="coverage-style-searchForm">
      <el-form-item>
        <div class="demo-input-suffix">
          <el-input prefix-icon="el-icon-search"
                    placeholder="请输入字段名称"
                    class="key-word-search"
                    clearable
                    v-model="searchWord">
          </el-input>
        </div>
      </el-form-item>
      <el-form-item>
        <el-select v-model="core"
                   placeholder="请输入字段类型"
                   clearable>
          <el-option v-for="item in cores"
                     :key="item.value"
                     :label="item.label"
                     :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <button @click="search"
                type="button"
                class="el-button el-button--primary el-button--medium h30Btn ">查询</button>
      </el-form-item>
      <!-- <el-form-item class="fr">
        <button @click="createField({name:'新建自定义字段'})"
                type="button"
                class="el-button el-button--primary el-button--medium h30Btn ">新建自定义字段</button>
      </el-form-item> -->
      <!-- 自定义的新建字段 -->
      <el-form-item class="fr">
        <button @click="createFieldForm({name:'新建自定义字段'})"
                type="button"
                class="el-button el-button--primary el-button--medium h30Btn ">新建自定义字段</button>
      </el-form-item>
    </el-form>
    <el-row>
      <!-- <el-table
        stripe
        border
        v-loading='loading'
        highlight-current-row
        :header-cell-style="{
          'background-color':'#F2F3F8',
          'border':'1px solid #e2e2e2',
          'border-right':'none'
        }"
        :cell-style="{
          'border-right':'none'
        }"
        :data="fieldTableData"
        style="width:100%"
        > -->
      <el-table stripe
                border
                v-loading='loading'
                :header-cell-style="{
          'background-color':'#F2F3F8',
        }"
                :data="fieldTableData"
                style="width:100%">
        <!-- <el-table-column
          label="日期"
          width="180">
          <template slot-scope="scope">
            <i class="el-icon-time"></i>
            <span >{{ scope.row.date }}</span>
          </template>
        </el-table-column> -->
        <el-table-column label="字段名称"
                         min-width="20%"
                         align="center">
          <template slot-scope="scope">
            <span class="label-name">{{ scope.row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column label="类型"
                         min-width="20%"
                         align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.type }}</span>
          </template>
        </el-table-column>
        <el-table-column label="来源"
                         min-width="20%"
                         align="center">
          <template slot-scope="scope">
            <span v-if="scope.row.source === 1">系统字段</span>
            <span v-else>自定义字段</span>
          </template>
        </el-table-column>
        <el-table-column label="操作"
                         align="center"
                         min-width="40%">
          <template slot-scope="scope">
            <el-button icon="el-icon-delete"
                       v-if="scope.row.source === 2"
                       type="text"
                       size="mini"
                       @click="handleDelete(scope.$index, scope.row)">删除</el-button>
            <el-button type="text"
                       size="mini"
                       class="run-and-stop"
                       @click="handleOff(scope.$index, scope.row)">
              <!-- <i class="el-icon-circle-check"></i> -->
              <img v-if="scope.row.useStatus !== 1"
                   src="../../../assets/images/start.png"
                   alt="">
              <img v-else
                   src="../../../assets/images/stop.png"
                   alt="">
              <span v-if="scope.row.useStatus !== 1">启用</span>
              <span v-else>停用</span>
            </el-button>
            <!-- v-if="scope.row.source === 2" -->
            <el-button icon="el-icon-edit"
                       type="text"
                       size="mini"
                       @click="handleEdit(scope.$index, scope.row, {name:'编辑自定义字段'})">编辑</el-button>
            <!-- 关联话术 -->
            <!-- <el-button v-if="scope.row.type == '单行文本' || scope.row.type == '多行文本'"
                       type="text"
                       size="mini"
                       @click="relateWords(scope.$index, scope.row)">关联话术</el-button> -->
          </template>
        </el-table-column>
      </el-table>
    </el-row>
    <el-row>
      <el-pagination background
                     class="page-foot-spacing el-pagination-style"
                     v-show="totalDataLength > 0"
                     @size-change="handleSizeChange"
                     @current-change="handleCurrentChange"
                     :current-page="page"
                     :page-sizes="[10, 20, 50, 100]"
                     :page-size="pageSize"
                     layout="total, sizes, prev, pager, next, jumper"
                     :total="totalDataLength"></el-pagination>
    </el-row>
    <!-- 关联话术弹框 -->
    <el-dialog title="关联话术"
              v-dialogDrag
               :visible.sync="dialogVisible"
               width="30%"
               :before-close="handleClose">
      <el-form :model="dialogVisibleForm"
               ref='dialogVisibleForm'>
        <el-form-item label='关键词：'>
          <el-input v-model="dialogVisibleForm.keyWord"
                    placeholder="请填写关键词，多个使用，隔开"></el-input>
        </el-form-item>
        <el-form-item label='添加推荐话术(请包含关键词)：'>
          <el-input v-model="dialogVisibleForm.keyDesc"
                    placeholder="请输入"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer"
            class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary"
                   @click="dialogSubmit('dialogVisibleForm')">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
// import { basicOptions } from '@/common/opntionsData.js'
import { updateUseStatus, deleteCustom, selectContentById, selectAllType, selectByNameAndType, selectAllOpen } from '@/api/customField.js'
export default {
  data () {
    return {
      dialogVisible: false,
      dialogVisibleForm: {
        keyWord: '',
        keyDesc: ''
      },
      loading: true,
      totalDataLength: 0,
      page: 1,
      pageSize: 10, // 每页最多显示几条数据
      fieldTableData: [],
      cores: [
        { value: 'all', label: '全部', ...this.cores }
      ],
      core: '',
      searchWord: ''
    }
  },
  mounted () {
    this.search()
    this.selectAllType()
    // 获取所有开启自定义字段
    this.selectAllOpen()
  },
  methods: {
    relateWords () {
      this.dialogVisible = true
    },
    dialogSubmit (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          // do something
          this.dialogVisible = false
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    // 自定义的新建字段
    createFieldForm (params) {
      this.$store.commit('isSystemFieldFun', false)
      this.$store.commit('customFieldIdFun', '')
      this.$store.commit('systemConfigTitFun', params)
      this.$router.push('./createCustomField')
    },
    // 搜索
    search () {
      this.page = 1
      this.getData()
    },
    getData () {
      let params = {
        name: this.searchWord,
        type: this.core,
        currentPage: this.page,
        pageSize: this.pageSize
      }
      selectByNameAndType(params).then(res => {
        let data = res.data
        if (data.retCode === 200) {
          this.loading = false
          this.fieldTableData = data.data
          this.totalDataLength = data.count
          if (this.fieldTableData.length <= 0) {
            this.page = this.page - 1
            this.getData()
          }
        }
      })
    },
    selectAllType () {
      selectAllType().then(res => {
        this.cores = res.data.data.reverse()
      })
    },
    // 搜索
    handleSizeChange (pageSize) {
      this.pageSize = pageSize
      this.search()
    },
    // 搜索
    handleCurrentChange (page) {
      this.page = page
      this.getData()
    },
    handleOff (index, row) {
      var useStatus = row.useStatus
      if (useStatus === 1) {
        useStatus = 0
      } else {
        useStatus = 1
      }
      let params = {
        id: row.id,
        userId: this.$store.state.userId,
        useStatus: useStatus
      }
      updateUseStatus(params).then(res => {
        if (res.data.retCode === 200) {
          this.search()
          this.selectAllOpen()
          this.$message({
            message: '修改成功',
            type: 'success'
          })
        }
      })
    },
    handleEdit (index, row, params) {
      if (row.source === 1) {
        this.$store.commit('isSystemFieldFun', true)
        sessionStorage.setItem('customField', JSON.stringify(row.source))
      } else {
        this.$store.commit('isSystemFieldFun', false)
        sessionStorage.setItem('customField', JSON.stringify(''))
      }
      this.$store.commit('systemConfigTitFun', params)
      this.$store.commit('customFieldIdFun', row.id)
      this.$router.push('/createCustomField')
      this.selectAllOpen()

      // selectContentById(row.id).then(res => {
      //   if (res.data.retCode === 200) {
      //     let formData = {
      //       type: 2,
      //       option: 2,
      //       widgetForm: res.data.data
      //     }
      //     this.selectAllOpen()
      //     sessionStorage.setItem('formData', JSON.stringify(formData))
      //     this.$store.commit('customFieldIdFun', row.id)
      //     // this.$router.push('/makeForm')
      //     this.$router.push('/createCustomField')
      //   } else {
      //     this.$message({
      //       message: res.data.msg,
      //       type: 'error'
      //     })
      //   }
      // })
    },
    handleDelete (index, row) {
      this.$confirm('确认要删除吗？', '确认删除', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        center: true,
        customClass: 'messageBox-prompt-delete'
      }).then(() => {
        deleteCustom(row.id).then(res => {
          var data = res.data
          if (data.retCode === 200) {
            this.getData()
            this.selectAllOpen()
            this.$message({
              message: '删除成功',
              type: 'success'
            })
          } else {
            this.$message({
              message: res.data.msg,
              type: 'error'
            })
          }
        })
      }).catch(() => {
      })
    },
    createField (params) {
      this.$store.commit('isSystemFieldFun', false)
      sessionStorage.setItem('customField', JSON.stringify(''))
      this.$store.commit('systemConfigTitFun', params)
      let formData = {
        type: 2,
        option: 1,
        widgetForm: []
      }
      sessionStorage.setItem('formData', JSON.stringify(formData))
      this.$router.push('/makeForm')
    },
    selectAllOpen () {
      selectAllOpen().then(res => {
        if (res.data.retCode === 200) {
          let data = res.data.data
          sessionStorage.setItem('customData', JSON.stringify(data))
        }
      })
    }
  }
}
</script>
<style scoped>
.top-input {
  margin-right: 20px;
}

.key-word-search {
  width: 350px;
}

.coverage-style-searchForm .el-input--suffix .el-input__inner {
  width: 240px;
}


.page-foot-spacing  .el-select .el-input .el-select__caret {
  color: #c0c4cc;
}

.label-name {
  color: #2393f1;
}

.no-use {
  color: #d2d1cf;
}

.el-button > i {
  font-size: 13px;
  margin-right: 10px;
}

.el-input__icon {
  font-size: 13px;
  font-weight: 800;
}

.el-input--prefix .el-input__inner {
  padding-left: 35px;
}

.el-pagination {
  text-align: right;
  padding: 20px 0;
}
.el-dialog__body {
  padding: 0 20px;
}
</style>
